package com.hms.service;

import com.hms.model.Booking;
import com.hms.repository.BookingRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Optional;

@Service("bookingService")
@Transactional
public class BookingService {

    @Autowired
    private BookingRepository bookingRepository;

    public Booking findById(int id) {
        Optional<Booking> tmp = bookingRepository.findById(id);
        return tmp.orElse(null);
    }

    public Booking findByRoomId(final int id) {
        return bookingRepository.findByRoomId(id);
    }

    public List<Booking> findByUserId(final int id) {
        return bookingRepository.findByUserId(id);
    }

    public List<Booking> findByTypeId(final int id) {
        return bookingRepository.findByRoomTypeId(id);
    }

    public void saveBooking(@NotNull Booking booking) {
        bookingRepository.save(booking);
    }

    public void updateBooking(@NotNull Booking booking) {
        Optional<Booking> entity = bookingRepository.findById(booking.getId());
        if (entity.isPresent()) {
            booking.setId(entity.get().getId());
            bookingRepository.save(booking);
        }
    }

    public void deleteBookingById(final int id) {
        bookingRepository.deleteById(id);
    }

    public void deleteBookingByRoomId(final int id) {
        bookingRepository.deleteByRoomId(id);
    }

    public void deleteBookingByUserId(final int id) {
        bookingRepository.deleteByUserId(id);
    }

    public List<Booking> findAllBookings() {
        return bookingRepository.findAll();
    }

    public boolean isBookingUnique(final int id, final int roomId) {
        Booking booking = findByRoomId(roomId);
        return ((booking == null) || (booking.getId() == id));
    }

    public List<Booking> findPendingBookings() {
        return bookingRepository.findByStatus("PENDING");
    }

    public List<Booking> findConfirmedBookings() {
        return bookingRepository.findByStatus("CONFIRMED");
    }

    public List<Booking> findCompletedBookings() {
        return bookingRepository.findByStatus("COMPLETED");
    }
}
